package org.common.eureka.service.fallback;

import com.alibaba.fastjson.JSONObject;
import feign.hystrix.FallbackFactory;
import org.common.eureka.service.IUserFeignClient;
import org.sam.commons.entity.pojo.SecUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class UserFeignClientFallbackFactory implements FallbackFactory<IUserFeignClient> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserFeignClientFallbackFactory.class);

    @Override
    public IUserFeignClient create(Throwable cause) {
        System.out.println("熔断原因 = " + cause);
        return new IUserFeignClient() {
            @Override
            public String queryJsonById(String id) {
                SecUser user = new SecUser();
                if (cause instanceof IllegalArgumentException) {
                    user.setId("-1");
                } else {
                    user.setId("-2");
                }
                user.setUserName("administrator");
                return JSONObject.toJSONString(user);
            }

            @Override
            public SecUser queryOne(String id) {
                //日志最好放在各个fallback方法中，而不要直接放在create方法中。
                //否则在引用启动时，就会打印该日志
                UserFeignClientFallbackFactory.LOGGER.info("fallback；reason was:" + cause);
                SecUser user = new SecUser();
                if (cause instanceof IllegalArgumentException) {
                    user.setId("-1");
                } else {
                    user.setId("-2");
                }
                user.setUserName("administrator");
                return user;
            }

            @Override
            public List queryAll() {
                //日志最好放在各个fallback方法中，而不要直接放在create方法中。
                //否则在引用启动时，就会打印该日志
                UserFeignClientFallbackFactory.LOGGER.info("fallback；reason was:" + cause);
                SecUser user = new SecUser();
                user.setId("-1");
                user.setUserName("administrator");
                return Stream.of(user).collect(Collectors.toList());
            }

            @Override
            public String queryJsonByName(String userName) {
                //日志最好放在各个fallback方法中，而不要直接放在create方法中。
                //否则在引用启动时，就会打印该日志
                UserFeignClientFallbackFactory.LOGGER.info("fallback；reason was:" + cause);
                SecUser user = new SecUser();
                if (cause instanceof IllegalArgumentException) {
                    user.setId("-1");
                } else {
                    user.setId("-2");
                }
                user.setUserName("administrator");
                return JSONObject.toJSONString(user);
            }
        };
    }
}
